package com.example.demo.service;

import com.example.demo.entity.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService {

    /**
     * 模拟获取数据
     * @return
     */
    public List<User> list() {
        User dong = new User(1L, "董事长", 0L);
        User zhao = new User(2L, "赵经理", 1L);
        User qian = new User(3L, "钱经理", 1L);
        User sun = new User(4L, "孙组长", 2L);
        User li = new User(5L, "李组长", 2L);
        User zhou = new User(6L, "周组长", 3L);
        User wu = new User(7L, "小吴", 4L);
        User zheng = new User(8L, "小郑", 5L);
        return Arrays.asList(dong, zhao, qian, sun, li, zhou, wu, zheng);
    }

    /**
     * 列表转树方法1
     * @return
     */
    public List<User> listToTree1() {
        List<User> list = list();
        List<User> tree = new ArrayList<>();
        for (User user : list) {
            //找到根节点
            if (user.getParentId() == null || user.getParentId().equals(0L)) {
                tree.add(user);
            }
            List<User> children = new ArrayList<>();
            //再次遍历list，找到user的子节点
            for (User node : list) {
                if (node.getParentId().equals(user.getId())) {
                    children.add(node);
                }
            }
            user.setChildren(children);
        }
        return tree;
    }

    /**
     * 列表转树方法2
     * @return
     */
    public List<User> listToTree2() {
        List<User> list = list();
        List<User> tree = new ArrayList<>();
        for (User user : list) {
            //找到根节点
            if (user.getParentId() == null || user.getParentId().equals(0L)) {
                tree.add(findChildren(user, list));
            }
        }
        return tree;
    }

    /**
     * 查找user的子节点
     * @param user
     * @param list
     * @return
     */
    private User findChildren(User user, List<User> list) {
        List<User> children = new ArrayList<>();
        for (User node : list) {
            if (node.getParentId().equals(user.getId())) {
                //递归调用
                children.add(findChildren(node, list));
            }
        }
        user.setChildren(children);
        return user;
    }

}
